import Request from "@/sdk/pocky-request/index.js"; //引入
import COMM from "@/common/common.js";
import idfa from "@/js_sdk/dc-idfa/idfa.js";
import {base64ToPath} from '@/js_sdk/image-tools/index.js'
/**
 * sys 系统模块,获取屏幕,系统
 */
const sys = {
	// 状态
	state: {
		sysInfo: uni.getSystemInfoSync(),
		initInfo: {
			"grules": "",
			"award": "",
			"open_city": [],
			"coupon": "",
			"approve": 0,
			"privacy": "",
			"search_keys": null,
			"enter_banner": {
				"icon": "",
				"url": "",
			},
			"policy": "",
			"refund": ""
		},
		MPToken:''

	},
	// 内部派生
	getters: {

	},
	// 同步方法 commit
	mutations: {
		initInfo: (state, payload) => {
			state.initInfo = payload
		},
		MPToken: (state, payload) => {
			state.MPToken = payload
		},
	},
	// 异步方法 dispatch
	actions: {
		/**
		 * @description  下载文件
		 * @param {Object} url  文件url
		 */
		downloadFile(context, fileUrl) {
			return new Promise((resolve, reject) => {
				uni.downloadFile({
					url: fileUrl,
					success: (res) => {
						if (res.statusCode == 200) {
							resolve(res.tempFilePath)
						} else {
							reject(res)
						}
					},
					fail: err => {
						console.log("文件下载失败:" + err);
						reject(err);
					}
				})
			})
		},
		/**
		 * @description  根据文件路径检查文件是否存在
		 * @param {Object} filePath
		 */
		hasFile(context, filePath) {
			return new Promise((resolve, reject) => {
				uni.getSavedFileList({
					success: (res) => {
						resolve(res.fileList.find(function(file) {
							return file.filePath = filePath
						}))
					},
					fail: (err) => {
						console.log("获取已下载的文件失败");
						reject(err)
					}
				})
			})
		},
		/**
		 * @description  安装更新
		 * @param {Object} filePath	更新包地址
		 */
		installUpdate(context, filePath) {
			return new Promise((resolve, reject) => {
				plus.runtime.install(filePath, {
					force: true
				}, function() { //安装成功
					resolve()
				}, function(err) { //安装失败
					console.log('安装失败:' + err);
					reject(err);
				});
			})
		},
		/**
		 * @description 存储文件
		 * @param {Object} tempFilePath
		 */
		saveFile(context, tempFilePath) {
			return new Promise((resolve, reject) => {
				uni.saveFile({
					tempFilePath: tempFilePath,
					success: function(res) {
						res.tempPath = tempFilePath
						console.log("存储文件成功，存储地址：" + res);
						resolve(res);
						// res.savedFilePath   存储后的路径
					},
					fail: (err) => {
						console.log("存储文件失败:" + err);
						reject(err);
					}
				});
			})
		},


		/**
		 * @description 删除指定路径的缓存文件
		 * @param {Object} filePath 文件的路径
		 */
		removeFileByPath(context, filePath) {
			return new Promise((resolve, reject) => {
				uni.removeSavedFile({
					filePath: filePath,
					success: () => {
						resolve()
					},
					fail: (reject) => {
						reject()
					},
					complete: function(res) {
						console.log("删除文件失败:" + err);
						reject(err)
					}
				});
			})
		},

		// 获取下载目录缓存文件大小
		getDownloadListSize(context) {
			let downloadSize = 0;
			return new Promise(resolve => {
				uni.getSavedFileList({
					success: (res) => {
						downloadSize = res.fileList.reduce(function(x, y) {
							return Number(x) + Number(y.size)
						}, 0);
						resolve(COMM.bytesToSize(downloadSize));
					},
					fail: (err) => {
						console.log("获取下载目录文件总大小失败");
					}
				})
			})
		},
		apiGetInit(context) {
			let _data = {};
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform == 'ios') {
				_data.channel = 10000;
			} else {
				_data.channel = plus.runtime.channel
			}
			// #endif
			// #ifdef H5
			_data.channel = 10000;
			// #endif
			_data.platform = uni.getSystemInfoSync().platform.toUpperCase()
			return new Promise((resolve, reject) => {
				Request().request({
					url: '/common/init.do',
					method: 'post',
					data: _data
				}).then(res => {
					if (res.data.code == 1) {
						uni.setStorageSync("initInfo", res.data.data)
						this.commit("initInfo", res.data.data)
						resolve(res)
					} else {
						this.commit("initInfo", uni.getStorageSync("initInfo"))
						reject(res)
					}
				})
			})
		},
		/**
		 * @description 获取搜索关键词
		 * @param {Object} context
		 */
		apiGetSearchWord(context) {
			return new Promise((resolve, reject) => {
				Request().request({
					url: '/mall/hot_keys.do',
					method: 'post',
					data: null
				}).then(res => {
					if (res.data.result == 1) {
						resolve(res)
					} else {

						reject(res)
					}
				})
			})
		},
		/**
		 * @description 获取第三方登录服务供应
		 * @param {Object} context
		 */
		uniGetLoginProvider(context) {
			return new Promise((resolve, reject) => {
				uni.getProvider({
					service: 'oauth',
					success: res => {
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				});
			})
		},
		/**
		 * @description 获取第三方分享服务供应
		 * @param {Object} context
		 */
		uniGetShareProvider(context) {
			return new Promise((resolve, reject) => {
				uni.getProvider({
					service: 'share',
					success: res => {
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				});
			})
		},
		shareText(context, _data) {
			switch (_data.provider) {
				case 'WXSceneSession':
					{
						uni.share({
							provider: "weixin",
							scene: "WXSceneSession",
							type: 1,
							summary: _data.text,
							success: function(res) {

							},
							fail: function(err) {

							}
						});
					}
					break;
				case 'WXSenceTimeline':
					{
						uni.share({
							provider: "weixin",
							scene: "WXSenceTimeline",
							type: 1,
							summary: _data.text,
							success: function(res) {

							},
							fail: function(err) {

							}
						});
					}
					break;
				case 'QQ':
					{
						if (plus.os.name == 'Android') {
							plus.runtime.launchApplication({
									pname: 'com.tencent.mobileqq'
								},
								function(e) {
									console.log('打开QQ失败' + e.message);
								}
							);
						} else if (plus.os.name == 'iOS') {
							plus.runtime.launchApplication({
								action: 'mqq://'
							}, function(e) {
								console.log('打开QQ失败: ' + e.message);
							});
						}
					}
					break;
				case 'sinaweibo':
					{
						uni.share({
							provider: "sinaweibo",
							type: 1,
							summary: _data.text,
							success: function(res) {

							},
							fail: function(err) {

							}
						});
					}
					break;
				default:
					break;
			}

		},
		/**
		 * 分享图文链接卡片
		 * @param {Object} context
		 * @param {Object} _data
		 */
		shareCard(context, _data) {
			_data.href=encodeURI(_data.href);
			console.log(_data);
			switch (_data.provider) {
				case 'WXSceneSession':
					{
						uni.share({
							provider: "weixin",
							scene: "WXSceneSession",
							type: 0,
							href: _data.href,
							title: _data.title,
							summary: _data.text,
							imageUrl: _data.img,
							success: function(res) {
								console.log("success:" + JSON.stringify(res));
							},
							fail: function(err) {
								console.log("fail:" + JSON.stringify(err));
							}
						});
					}
					break;
				case 'WXSenceTimeline':
					{
						uni.share({
							provider: "weixin",
							scene: "WXSenceTimeline",
							type: 0,
							title: _data.title,
							imageUrl: _data.img,
							href: _data.href,
							summary: _data.text,
							success: function(res) {

							},
							fail: function(err) {

							}
						});
					}
					break;
				case 'QQ':
					{
						if (uni.getSystemInfoSync().platform == 'ios') {
							uni.downloadFile({
								url:_data.img,
								success: (res) => {
									console.log(res.tempFilePath);
									uni.$emit("hide");
									uni.share({
										provider: "qq",
										type: 0,
										title: _data.title,
										imageUrl: res.tempFilePath,
										href:_data.href,
										summary: _data.text,
										success: function(res) {
											uni.$emit("hide");
											console.log(res);
										},
										fail: function(err) {
											uni.$emit("hide");
											console.log(err);
										}
									});
									
								}
							})
						} else {
							uni.downloadFile({
								url:_data.img,
								success: (res) => {
									uni.$emit("hide");
									uni.share({
										provider: "qq",
										type: 2,
										title: _data.title,
										imageUrl: res.tempFilePath,
										href: _data.href,
										summary: _data.text,
										success: function(res) {
											uni.$emit("hide");
											console.log(res);
										},
										fail: function(err) {
											uni.$emit("hide");
											console.log(err);
										}
									});
									
								}
							})

						}
					}
					break;
				case 'sinaweibo':
					{
						uni.downloadFile({
							url:_data.img,
							success: (res) => {
								console.log(res.tempFilePath);
								uni.$emit("hide");
								uni.share({
									provider: "sinaweibo",
									type: 0,
									title: _data.title,
									imageUrl: res.tempFilePath,
									href:_data.href,
									summary: _data.text,
									success: function(res) {
										uni.$emit("hide");
										console.log(res);
									},
									fail: function(err) {
										console.log(err);
										uni.$emit("hide");
									}
								});
								
							}
						})
						

					}
					break;
				case "miniProgram":
					{
						uni.share({
						    provider: 'weixin',
						    scene: "WXSceneSession",
						    type: 5,
						    imageUrl:  _data.img,
						    title: _data.title,
						    miniProgram: {
						        id: 'gh_f52f8b3ee66c',
						        path: _data.href,
						        // type: 0,	//正式版
								type:2,		//体验版
						        webUrl: 'http://s.de123.com/#/pages/'+_data.href
						    },
						    success: ret => {
						        // console.log(JSON.stringify(ret));
						    }
						});
					}
					break;
				default:
					break;
			}
		},
		/**
		 * @description  分享海报图到微信会话或朋友圈
		 * @param {Object} context
		 * @param {Object} _data
		 */
		shareImg(context,_data){
			switch (_data.provider) {
				case 'WXSceneSession':
					{
						uni.share({
							provider: "weixin",
							scene: "WXSceneSession",
							type: 2,
							imageUrl: _data.img,
							success: function(res) {
								console.log("success:" + JSON.stringify(res));
							},
							fail: function(err) {
								console.log("fail:" + JSON.stringify(err));
							}
						});
					}
					break;
				case 'WXSenceTimeline':
					{
						uni.share({
							provider: "weixin",
							scene: "WXSenceTimeline",
							type: 2,
							imageUrl: _data.img,
							success: function(res) {
			
							},
							fail: function(err) {
			
							}
						});
					}
					break;
				default:
					break;
			}
		},
		/**
		 * 获取感兴趣内容
		 * @param {Object} context
		 */
		apiGetInterest(context) {
			return new Promise((resolve, reject) => {
				Request().request({
					url: '/common/guide/list.do',
					method: 'post',
					data: {}
				}).then(res => {
					resolve(res)
				}).catch(err => {
					reject(res)
				})
			})
		},
		/**
		 * @description 日志上报
		 * @param {Object} context
		 * @param {Object} _data
		 * type:   1 课程    2店铺
		 */
		apiReporgLog(context, _data) {
			// #ifdef APP-PLUS
			return new Promise((resolve, reject) => {
				let _postData = {};
				// IMEI获取
				if (uni.getSystemInfoSync().platform == 'android') {
					let _imei = '';
					if (plus.device.imei.indexOf(',') > 0) {
						_imei = plus.device.imei.split(',')[0]
					} else {
						_imei = plus.device.imei
					}
					_postData.imei = _imei;
					_postData.channel = plus.runtime.channel;
				} else {
					_postData.imei = idfa.value();
					_postData.channel = 10000;
				}

				// userId
				if (context.rootState.user.isLogin) {
					_postData.userId = context.rootState.user.userInfo.userId
				}
				// 兴趣
				_postData.guideCate = uni.getStorageSync('xinqu').join(',')
				_postData.city = context.rootState.map.locationCity.adcode;
				_postData.version = context.rootState.upDate.nowAppInfo.version;
				_postData.pushId = plus.push.getClientInfo().clientid
				_postData.network = context.rootState.netWork.nowNetType;
				_postData.brand = context.state.sysInfo.brand;
				_postData.model = context.state.sysInfo.model;
				_postData.type = parseInt(_data.type);
				_postData.linkId = parseInt(_data.linkId);
				console.log(_postData);
				Request().request({
					url: '/common/log.do',
					method: 'post',
					data: _postData
				}).then(res => {
					console.log(res);
					resolve(res)
				}).catch(err => {
					reject(res)
				})
			})
			// #endif

		},
		/**
		 * @description  获取小程序token
		 * @param {Object} context
		 */
		apiGetMPToken(context){
			return new Promise((resolve, reject) => {
				Request().request({
					url: '/pay/wx/mpAccToken.do',
					method: 'get',
				}).then(res => {
					this.commit("MPToken",res.data.data.access_token)
					resolve(res)
				}).catch(err => {
					reject(res)
				})
			})
		},
		/**获取小程序码
		 * @param {Object} context
		 * @param {Object} _data
		 */
		apiGetMpCodeImg(context,_data){
			// _data=JSON.stringify(_data)
			return new Promise((resolve, reject) => {
				Request().request({
					url: '/common/genMpCode.do',
					method: 'post',
					data:_data
				}).then(res => {
					console.log(res);
					resolve(res);
				}).catch(err => {
					reject(res)
				})
				// Request().request({
				// 	url: 'https://test.hawklu.com/getMPcode.php',
				// 	method: 'post',
				// 	data:_data
				// }).then(res => {
				// 	console.log(res);
				// 	resolve(res);
				// }).catch(err => {
				// 	reject(res)
				// })
			})
		}
	}
}

export default sys
